package com.hmdp;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class BatchRegisterSimulator {

    private static final String URL = "http://localhost:8081/user/batch"; // 修改为你的接口地址
    private static final int USER_COUNT = 1000;
    private static final String OUTPUT_FILE = "tokens.txt";

    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE))) {
            for (int i = 1; i <= USER_COUNT; i++) {
                String phone = String.format("138%08d", i); // 模拟手机号
                String code = "123456";                     // 假设统一验证码
                String password = "123456";                 // 假设统一密码

                String token = loginAndGetToken(phone, code, password);
                if (token != null) {
                    writer.write(token);
                    writer.newLine();
                    System.out.println("用户 " + phone + " 登录成功，token: " + token);
                } else {
                    System.out.println("用户 " + phone + " 登录失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("全部用户模拟完成，token 已写入 " + OUTPUT_FILE);
    }

    private static String loginAndGetToken(String phone, String code, String password) {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(URL);
            post.setHeader("Content-Type", "application/json;charset=UTF-8");

            // 构造 JSON 请求体
            String json = String.format(
                    "{\"phone\":\"%s\", \"code\":\"%s\", \"password\":\"%s\"}",
                    phone, code, password
            );
            post.setEntity(new StringEntity(json, StandardCharsets.UTF_8));

            try (CloseableHttpResponse response = client.execute(post)) {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode root = mapper.readTree(response.getEntity().getContent());
                // 假设 token 在 data 字段
                if (root.has("data")) {
                    return root.get("data").asText();
                }
            }
        } catch (IOException e) {
            System.err.println("请求失败: " + e.getMessage());
        }
        return null;
    }
}

